using Command;
using QFramework;
using UnityEngine;

namespace ViewController.Gameplay
{
    public class Player : ShootingEditor2DController
    {
        private Trigger2DCheck _groundCheck;

        private Gun _gun;
        private bool _jumpPressed;

        private Rigidbody2D _rigidbody2D;

        private void Awake()
        {
            _rigidbody2D = GetComponent<Rigidbody2D>();

            _groundCheck = transform.Find("GroundCheck").GetComponent<Trigger2DCheck>();

            _gun = transform.Find("Gun").GetComponent<Gun>();
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.K)) _jumpPressed = true;

            if (Input.GetKeyDown(KeyCode.J)) _gun.Shoot();

            if (Input.GetKeyDown(KeyCode.R)) _gun.Reload();

            if (Input.GetKeyDown(KeyCode.Q)) this.SendCommand<ShiftGunCommand>();
        }

        private void FixedUpdate()
        {
            var horizontalMovement = Input.GetAxis("Horizontal");

            var localScale = transform.localScale;
            if (horizontalMovement < 0 && localScale.x > 0 ||
                horizontalMovement > 0 && localScale.x < 0)
            {
                localScale.x = -localScale.x;
                transform.localScale = localScale;
            }

            _rigidbody2D.velocity = new Vector2(horizontalMovement * 5, _rigidbody2D.velocity.y);

            var grounded = _groundCheck.Triggered;

            if (_jumpPressed && grounded) _rigidbody2D.velocity = new Vector2(_rigidbody2D.velocity.x, 5);

            _jumpPressed = false;
        }
    }
}